<template>
  <div id="zlh-main-box">
    <div class="zlh-default-background-color" style="padding: 1.5rem;">
      <el-space direction="vertical" alignment="left" size="large">
        <div>
          <el-breadcrumb separator="/">
            <el-breadcrumb-item :to="{ path: '/' }"> <el-icon><House /></el-icon></el-breadcrumb-item>
            <el-breadcrumb-item>文章管理</el-breadcrumb-item>
          </el-breadcrumb>
        </div>
        <div>
        <div style="padding: 1rem"><h2>文章管理</h2></div>
        </div>
      </el-space>
    </div>
    <div class="zlh-flex-column-default">
      <div class="zlh-search zlh-default-background-color">
        <el-form :inline="true" :model="filters" class="demo-form-inline">
          <el-form-item label="文章标题">
            <el-input v-model="filters.article_title" placeholder="文章标题" clearable/>
          </el-form-item>
          <el-form-item label="文章类型">
            <el-select v-model="filters.article_type_id" placeholder="文章类型" clearable>
              <el-option :key=selectDataI v-for="(selectDataV,selectDataI) in articleList.selectData"  :label=selectDataV.article_type_name :value=selectDataV.article_type_id />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSearch">搜索</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="zlh-table-box">
        <div class="zlh-table-box-header">
          <span class="zlh-table-box-title">文章列表</span>
          <div class="zlh-table-box-operation">
            <el-button type="primary"  @click="onInsert" >新增文章</el-button>
          </div>
        </div>
        <div class="zlh-table">
          <el-table :data="articleList.tableData" style="width: 100%">
            <el-table-column fixed prop="article_id" label="ID" width="80" />
            <el-table-column prop="article_title" label="标题" width="120" />
            <el-table-column prop="create_time" label="创建日期" width="120" />
            <el-table-column prop="article_type_str" label="类型" width="120" />
            <el-table-column prop="article_tips_str" label="标签" width="120" />
            <el-table-column prop="page_view" label="点击量" width="120" />
            <el-table-column
                prop="tag"
                label="状态"
                width="100"
                :filters="[
                  { text: '启用', value: 1 },
                  { text: '禁用', value: 2 },
                ]"
                :filter-method="filterTag"
            >
              <template #default="scope">
                <el-tag :type="scope.row.enable_status === '启用' ? '' : 'danger'">{{ scope.row.enable_status}}</el-tag>
              </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作" width="120">
              <template #default = "scope">
                <el-button link type="primary" size="small" @click="onEdit(scope.row)">编辑</el-button>
                <el-button link type="primary" size="small" v-if="scope.row.enable_status === '禁用'" @click="onStart(scope.row)">启用</el-button>
                <el-button link type="primary" size="small" v-if="scope.row.enable_status === '启用' " @click="onEnd(scope.row)">禁用</el-button>
                <el-button link type="primary" size="small" @click="onDelete(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="zlh-page">

          <el-pagination   background layout="prev, pager, next"
                           :total = total.total
                           :page-size = 5
                           @next-click = "nextClick"
                           @prev-click = "prevClick"
                           @current-change="currentChange" />
        </div>
      </div>
    </div>
  </div>
  <el-dialog
      v-model="dialogVisible"
      :title="diaTitle"
      width="50%"
      :before-close="handleClose"
  >
    <el-form :model="addForm" label-width="120px">
      <el-form-item label="标题">
        <el-input v-model="addForm.article_title" clearable />
      </el-form-item>
      <el-form-item label="类型">
        <el-select v-model="addForm.article_type_id" placeholder="文章类型" clearable>
          <el-option :key=selectDataI v-for="(selectDataV,selectDataI) in articleList.selectData"  :label=selectDataV.article_type_name :value=selectDataV.article_type_id />
        </el-select>
      </el-form-item>
      <el-form-item label="标签">
        <el-checkbox-group v-model="addForm.article_tips">
          <el-checkbox :key=index v-for="(item,index) in articleList.tips" :label=item.article_tips_name />
        </el-checkbox-group>
      </el-form-item>
      <el-form-item label="附件地址获取">
        <el-upload
            v-model:file-list="fileAddr"
            class="upload-demo"
            action="https://apia.zlhranhou.com/index.php/api/uploadImg"
            multiple
            name="file"
            :on-success = "fileAddrSuccess"
            :limit="1"
        >
          <el-button type="primary">上传地址获取</el-button>
          <template #tip>
            <div class="el-upload__tip">
            用于获取Markdown中的地址路由
            </div>
          </template>
        </el-upload>
      </el-form-item>
      <el-form-item label="地址:">
        <p id="copy">{{fileAddrStr}}</p>
        <el-button @click="copyLink" class="tag" style="margin-left: 20px">复制</el-button>
      </el-form-item>
      <el-form-item label="附件">
        <!--            action="http://localhost/zlhranhou-lar/public/index.php/api/upload"-->
        <el-upload
            v-model:file-list="fileList"
            class="upload-demo"
            action="https://apia.zlhranhou.com/index.php/api/upload"
            multiple
            :limit="3"
            :on-exceed="fileExceed"
        >
          <el-button type="primary">附件上传</el-button>
          <template #tip>
            <div class="el-upload__tip">
             用于上传面试音频等 不超过50M
            </div>
          </template>
        </el-upload>
      </el-form-item>
      <el-form-item label="正文">
        <v-md-editor  v-model="addForm.article_content" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="sendText()">保存</el-button>
      </span>
    </template>
  </el-dialog>
</template>


<script lang="ts" setup>
import {
  House,
} from '@element-plus/icons-vue'
import {reactive, ref,} from 'vue'
import { ElMessage,ElMessageBox,ElNotification  } from 'element-plus'
import type { UploadUserFile } from 'element-plus'
// api
import article from '@/api/article.js'
import articleType from '@/api/articleType.js'
import articleTips from '@/api/articleTips.js'

import system from '@/api/system.js'

import Clipboard from 'clipboard'

// do not use same name with ref
const addForm = reactive({
  article_content:'',
  article_type_id:'',
  article_title:'',
  article_tips:[],
  article_id:0,
})
let dialogVisible = ref(false)
let diaTitle = ref('新增博客')

let editFlag = true;

// eslint-disable-next-line no-undef
const fileList = ref<UploadUserFile[]>([])
const fileAddr = ref<UploadUserFile[]>([])
let fileAddrStr = ref<string>("")

function copyLink () {
  let clipboard = new Clipboard('.tag', {
    text: function () {
      if(fileAddrStr.value != ""){
        return fileAddrStr.value
      }
      return "-"
    }
  })
  clipboard.on('success', e => {
    // 释放内存
    clipboard.destroy()
  })
  clipboard.on('error', e => {
    clipboard.destroy()
  })
  clipboard.onClick(event)
}

function fileAddrSuccess(){
  if(fileAddr.value[0].response.data.file_id === undefined){
    ElMessage.error("文件格式错误,仅允许上传图片")
  }else{
    fileAddrStr.value = "http://apia.zlhranhou.com/index.php/api/download?file_id="+fileAddr.value[0].response.data.file_id
  }

  // fileAddr.value[0].response.data 文件ID
  fileAddr.value = [];

}



function fileExceed(){
  ElNotification({
    title: '提示',
    message: "超出最大上传数量",
  })
}


function onEdit(row:any){
  dialogVisible.value = true
  editFlag = false;
  diaTitle.value = "编辑博客"
  getArticleInfo(row.article_id)
}

function onInsert(){
  addForm.article_tips = [];
  addForm.article_type_id = '';
  addForm.article_content = '';
  addForm.article_title = '';
  dialogVisible.value = true
  editFlag = true;
}

function getArticleInfo(articleId:number):any{
  article.getArticleInfo(articleId)
      .then((res: any) => {
        let data = res.data;
        addForm.article_tips = data.article_tips_ids;
        addForm.article_type_id = data.article_type_id;
        addForm.article_content = data.article_content;
        addForm.article_title = data.article_title;
        addForm.article_id = data.article_id;
        fileList.value = JSON.parse(data.files)
        dialogVisible.value = true
      })
      .catch((error: any)=>{
        ElMessage.error("网络异常")
        console.log(error)
      });
}


function onStart(row:any){
  article.editArticle(row.article_id,{
    enable_status:1
  })
      .then((res: any) => {
        if(res.ok==="ok"){
          ElMessage.success("启用成功")
          getArticleList(page)
        }
      })
      .catch((error: any)=>{
        ElMessage.error("网络异常")
        console.log(error)
      })
}

function onEnd(row:any){
  article.editArticle(row.article_id,{
    enable_status:2
  })
      .then((res: any) => {
        if(res.ok==="ok"){
          ElMessage.success("禁用成功")
          getArticleList(page)
        }
      })
      .catch((error: any)=>{
        ElMessage.error("网络异常")
        console.log(error)
      })
}

function onDelete(row:any){
  article.editArticle(row.article_id,{
    status:2
  })
      .then((res: any) => {
        if(res.ok==="ok"){
          ElMessage.success("删除成功")
          getArticleList(page)
        }
      })
      .catch((error: any)=>{
        ElMessage.error("网络异常")
        console.log(error)
      })
}


function sendText(){
  let article_tips_ids = [];
  let hashTips = getTipsIds();
  addForm.article_tips.forEach((value, index)=>{
    article_tips_ids.push(hashTips[value])
  });
  let sendForm = {
    article_content:addForm.article_content,
    article_type_id:addForm.article_type_id,
    article_title:addForm.article_title,
    article_tips_ids:article_tips_ids,
    files:fileList.value
  }
  if(editFlag){
    article.addArticle(sendForm)
        .then((res: any) => {
          if(res.ok==="ok"){
            ElMessage.success("新增成功")
            dialogVisible.value = false
            getArticleList(page)
          }
        })
        .catch((error: any)=>{
          ElMessage.error("网络异常")
          console.log(error)
        })
  }else{
    article.editArticle(addForm.article_id,sendForm)
        .then((res: any) => {
          if(res.ok==="ok"){
            ElMessage.success("编辑成功")
            dialogVisible.value = false
            getArticleList(page)
          }
        })
        .catch((error: any)=>{
          ElMessage.error("网络异常")
          console.log(error)
        })
  }


}

const filterTag = (value: string, row: any) => {
  console.log("赛选了tag")
}

const filters = reactive({
  article_title: '',
  article_type_id: '',
})

const onSearch = () => {
  getArticleList(page,filters)
}

let articleList = reactive({
  tableData:[],
  selectData:[],
  tips:[]
})


let page = 1;
let total = reactive({
  total:0
})

getData();
function getData(){
  getArticleList(page);
  getArticleTypeSelect();
  getArticleTipsSelect();
}

function getTipsIds(){
  let tipsHash = [];
  articleList.tips.forEach((value)=>{
      tipsHash[value.article_tips_name] = value.article_tips_id
  })
  return tipsHash;
}

function getArticleTipsSelect(){
  articleTips.getArticleTipsSelect()
      .then((res: any) => {
        let resData =  res.data;
        articleList.tips = resData
        getTipsIds()
      })
      .catch((error: any)=>{
        ElMessage.error("网络异常")
        console.log(error)
      })
}

function getArticleTypeSelect(){
  articleType.getArticleTypeSelect()
      .then((res: any) => {
        let resData =  res.data;
        articleList.selectData = resData
      })
      .catch((error: any)=>{
        ElMessage.error("网络异常")
        console.log(error)
      })
}

function getArticleList(page: number,filters = {}){
  let args = {
    current_page:page,
    filters:filters
  }
  article.getArticleList(args)
      .then((res: any) => {
        let resData =  res.data.data;
        total.total = res.data.total
        articleList.tableData = resData
      })
      .catch((error: any)=>{
        ElMessage.error("网络异常")
        console.log(error)
      })
}



const handleClose = (done: () => void,flag = false) => {
  ElMessageBox.confirm('是否要关闭编辑页？').then(()=>{
    getArticleList(page)
    done()
  }).catch(() => {
    // catch error
  })

}



function nextClick(cur_page:number){
  if(cur_page < total.total){
    page++;
    getArticleList(page)
  }
}

function prevClick(cur_page:number){
  if(cur_page > 1){
    page--;
    getArticleList(page)
  }
}

function currentChange(cur_page:number){
  page = cur_page
  getArticleList(page)
}
</script>

<style scoped>
.dialog-footer button:first-child {
  margin-right: 10px;
}
</style>
